<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>博客列表页</title>
    <link
      rel="stylesheet"
      href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css"
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
      crossorigin="anonymous"
    />
		<link rel="stylesheet" href="./common.css">
    <style type="text/css"></style>
  </head>
  <body>
    <div class="container">
      <div class="row justify-content-md-center">
        <div class="col-lg-8 col-md-12">
          <h1 class="display-4">博客列表页</h1>
          <ul class="blog-list list-unstyled" id="blogWrapper"></ul>
        </div>
      </div>
    </div>

    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script src="https://cdn.bootcss.com/moment.js/2.23.0/moment.min.js"></script>
    <script src="https://cdn.bootcss.com/moment.js/2.23.0/locale/zh-cn.js"></script>
    <script>
      // 发送 get 请求
      function get(url) {
        return $.get(url);
      }

      // 显示格式化的时间
      function getFormatDate(dt) {
        return moment(dt).format("LL");
      }

      // 获取 url 参数
      function getUrlParams() {
        let paramStr = location.href.split("?")[1] || "";
        paramStr = paramStr.split("#")[0];
        const result = {};
        paramStr.split("&").forEach(itemStr => {
          const arr = itemStr.split("=");
          const key = arr[0];
          const val = arr[1];
          result[key] = val;
        });
        return result;
      }

      // 获取 dom 元素
      const $container = $("#blogWrapper");

      // 拼接接口 url
      let url = "/api/blog/list";
      const urlParams = getUrlParams();
      if (urlParams.author) {
        url += "?author=" + urlParams.author;
      }

      // 加载数据
      get(url).then(res => {
        if (res.errno !== 0) {
          alert("数据错误");
          return;
        }

        // 遍历博客列表，并显示
        const data = res.data || [];
        data.forEach(item => {
          $container.append(
            $(`
							<li class="title-wrapper">
								<p class="title">
									<a href="/detail.html?id=${item.id}">${item.title}</a>
								</p>
								<div class="info-wrapper">
									<span>
										作者：<a href="/index.html?author=${item.author}">${item.author}</a>
									</span>
									<span>${getFormatDate(item.createtime)}</span>
								</div>
							</li>
						`)
          );
        });
      });
    </script>
  </body>
</html>
